from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
import json
from ihome.utils.view import LoginRequiredMixin
import datetime
from homes.models import House
from order.models import Order


class OrderCommitView(LoginRequiredMixin, View):

    def post(self, request):
        '''接收参数, 保存订单信息'''

        # 1.接收json参数(address_id, pay_method)
        dict = json.loads(request.body.decode())
        house_id = dict.get('house_id')
        start_date = dict.get('start_date')
        end_date = dict.get('end_date')

        # 2.总体检验
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': "4103",
                                 'errmsg': "缺少必传参数"})

        # 在house表中以user_id取出用户所有的house.id
        try:
            user_id = House.objects.filter(house_id=house_id).user_id
            # 判断用户id 与 房主的id是否相同
            if request.user.id == user_id:
                return JsonResponse({'errno': "4003",
                                     'errmsg': "用户已存在"})
        except Exception as e:
            return JsonResponse({'errno': "4001",
                                 'errmsg': "用户数据错误"})

        # 进行日期判断,找出这个房子的所有订单
        try:
            order_list = Order.objects.filter(house_id=house_id)

            # 遍历订单中的所有预定时间,有相同的就不能下单
            for order in order_list:
                date = (order.begin_date, order.end_date)
                order_date = (start_date, end_date)
                # 判断该时间段是否此房子有订单
                if order_date == date:
                    return JsonResponse({'errno': "4001",
                                         'errmsg': "用户数据错误"})

        except Exception as e:
            return JsonResponse({'errno': "4001",
                                 'errmsg': "用户数据错误"})

        # house的user_id 与request.user.id无联系,则创建订单表,id自动生成

        # 生成住房天数
        start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
        end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        days = end_date - start_date

        # 生成住房 价格
        try:
            house_price = House.objects.filter(id=house_id).price
            # 订单总金额
            amount = house_price * days
        except Exception as e:
            return JsonResponse({'errno': "4301",
                                 'errmsg': "订单数据查找失败"})

        try:
            order = Order.objects.create(
                house_id=house_id,
                start_date=start_date,
                end_date=end_date,
                days=days,
                price=house_price,
                amount=amount,
                user_id=request.user.id
            )

        except Exception as e:
            return JsonResponse({'errno': "4302",
                                 'errmsg': "订单数据保存失败"})
        # 添加成功 返回json
        return JsonResponse({'errno': "0",
                             'errmsg': "ok",
                             'order_id': order.id})


        # '''获取订单必须先登录,查询字符串传参
        # 判读role是房东还是房客,房东可以拒单'''

    def get(self, request):
        # 以user_id在订单表里 获取该用户的全部的订单
        role = request.GET.get('role')
        user_id = request.user.id
        if role not in ['custom', 'landlord']:
            return JsonResponse({'errno': "4103",
                                 'errmsg': '参数错误'})

        if role == 'custom':
            # 用户custom的订单返回以下情况

            try:
                order_list = Order.objects.filter(user_id=user_id)

            except Exception as e:
                return JsonResponse({'errno': "4301",
                                     'errmsg': "订单数据查找失败"})
                # 遍历订单列表 添加数据
            orders = []
            for order in order_list:
                orders.append({
                    # 订单id
                    "order_id": order.id,
                    # 订单金额 二位小数
                    "amount": '%.2f' % order.amount,
                    # 订单评论
                    "comment": order.comment,
                    # 创建时间
                    "ctime": order.create_time,
                    # 入住天数
                    "days": order.days,
                    # 入住日期
                    "start_date": order.begin_date,
                    # 离开日期
                    "end_date": order.end_date,
                    # 图片地址
                    "img_url": order.house.index_image_url,
                    # 订单状态
                    "status": order.status,
                    # 房屋标题
                    "title": order.house.title
                })


        else:
            # 房主的订单
            try:
                # 先找到房主的所有的房子
                house_list = House.objects.filter(user_id=user_id)

            except Exception as e:
                return JsonResponse({'errno': "4301",
                                     'errmsg': "订单数据查找失败"})
            try:
                # 以house_id 获取所有的订单
                orders = []
                for house in house_list:
                    # 获取房东所有的房子
                    order_list = Order.objects.filter(house_id=house.id)

                    # 以订单号获取所有的订单信息
                    for order in order_list:
                        orders.append({
                            # 订单id
                            "order_id": order.id,
                            # 订单金额 二位小数
                            "amount": '%.2f' % order.amount,
                            # 订单评论
                            "comment": order.comment,
                            # 创建时间
                            "ctime": order.create_time,
                            # 入住天数
                            "days": order.days,
                            # 入住日期
                            "start_date": order.begin_date,
                            # 离开日期
                            "end_date": order.end_date,
                            # 图片地址
                            "img_url": order.house.index_image_url,
                            # 订单状态
                            "status": order.status,
                            # 房屋标题
                            "title": order.house.title
                        })

            except Exception as e:
                return JsonResponse({'errno': "4301",
                                     'errmsg': "订单数据查找失败"})

        return JsonResponse({'errno': "0",
                             'errmsg': "ok",
                             'data': {"orders": orders}})


class OrderActive(View):
    '''对订单请求做出接受或者拒绝'''

    def put(self, request, order_id, status):

        # 以order_id 获取订单对象
        dict = json.loads(request.body.decode())
        order_id = order_id
        status = status

        # 判断action的值 接单
        if dict.acction == 'accept':

            # 查找待支付的订单对象 并更新状态
            try:
                Order.objects.filter(id=order_id, status=status).update(status='1')

                return JsonResponse({'errno': "0",
                                     'errmsg': "操作成功"})

            except Exception as e:
                return JsonResponse({'errno': "4301",
                                     'errmgs': "订单查询失败"})

        elif dict.acction == 'reject':
            # 如果拒单 前段会传拒绝原因
            reason = dict.reason
            # 判断有无理由
            if not reason:
                return JsonResponse({'errno': "4002",
                                     'errmsg': "缺少必传参数"})
            # 找出订单对象 改状态为拒单
            try:
                Order.objects.filter(id=order_id, status=status).update(status='6')

                return JsonResponse({'errno': "0",
                                     'errmsg': "操作成功"})
            except Exception as e:
                return JsonResponse({'errno': "4301",
                                     'errmsg': "订单查询失败"})


class OrderComment(View):
    '''对订单进行评价'''

    def put(self, request, order_id, comment):
        # 路径传参接收参数
        order_id = order_id
        comment = comment
        try:
            # 以订单id找出 未评价的对应的订单
            Order.objects.filter(id=order_id, status=3).update(comment=comment, status=4)

        except Exception as e:
            return JsonResponse({'errno': "4301",
                                 'errmsg': "订单查找出错"})
        return JsonResponse({'errno': "0",
                             'errmsg': "操作成功"})
